package ay.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

public class AnaService {
	private String URL = "http://www.miui.com/forum.php";
	private String CAHRSET = "UTF-8";
	private static List<Map> analist = null;
	private static AnaService instance = null;

	private AnaService() {
		analist = new ArrayList();
		String regex = "<script type=\"text/javascript\">var mottoData = (\\{[\\s\\S]*\\});</script>";
		ArrayList<String> list = HtmlParser.getHtmlContentByRegex(URL, CAHRSET, regex);
		String anaJson = list == null ? null : list.get(0);
		if (anaJson != null) {
			try {
				JSONObject anas = new JSONObject(anaJson);
				Iterator ie = anas.keys();
				while (ie.hasNext()) {
					JSONObject ana = anas.getJSONArray(ie.next().toString()).getJSONObject(0);
					Map map = new HashMap<String, String>();
					String content = ana.getString("content");
					content = content.replaceAll("[-,－,_,——]+[\\S\\s]*", "");
					map.put("content", content);
					map.put("pic", ana.getString("pic"));
					analist.add(map);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	public static AnaService getInstance() {
		if (instance == null || analist == null || analist.size() < 1) {
			return new AnaService();
		} else {
			return instance;
		}
	}

	public Map<String, String> getAna() {
		Map anaMap = new HashMap<String, String>();
		if (analist == null || analist.size() < 1) {
			instance = new AnaService();
		}
		int index = new Random().nextInt(analist.size());
		anaMap = analist.get(index);
		analist.remove(index);
		return anaMap;
	}

}
